import java.util.LinkedList;
import java.util.Queue;

/**
 * 1020. 飞地的数量
 * https://leetcode.cn/problems/number-of-enclaves/description/
 */
class Solution {
    int m, n;
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    boolean[][] vist;
    public int numEnclaves(int[][] grid) {
        m = grid.length; n = grid[0].length;
        vist = new boolean[m][n];

        Queue<int[]> q = new LinkedList<>();
        for(int i = 0; i < m; i++) {
            //第一列
            if(grid[i][0] == 1) {
                q.add(new int[]{i , 0});
                vist[i][0] = true;
            }
            //最后一列
            if(grid[i][n - 1] == 1) {
                q.add(new int[]{i, n - 1});
                vist[i][n - 1] = true;
            }
        }
        for(int i = 0; i < n; i++) {
            //最后一行
            if(grid[m - 1][i] == 1) {
                q.add(new int[]{m - 1, i});
                vist[m - 1][i] = true;;
            }
            //第一行
            if(grid[0][i] == 1) {
                q.add(new int[]{0, i});
                vist[0][i] = true;;
            }
        }
        //多源bfs
        while(!q.isEmpty()) {
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            for(int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && grid[x][y] == 1) {
                    q.add(new int[]{x, y});
                    vist[x][y] = true;
                }
            }
        }
        int ret = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(!vist[i][j] && grid[i][j] == 1) ret++;
            }
        }
        return ret;
    }
}